package main

import (
	"fmt"
	"gitee.com/worklz/grpc-mtls-demo/server-order/config"
	"gitee.com/worklz/grpc-mtls-demo/server-order/handler"
	_ "gitee.com/worklz/grpc-mtls-demo/server-order/pkg/boot"
	"gitee.com/worklz/grpc-mtls-demo/server-order/pkg/shutdown"
	"gitee.com/worklz/grpc-mtls-demo/server-order/pkg/util"
	orderpb "gitee.com/worklz/grpc-mtls-demo/server-order/proto/order"
	"google.golang.org/grpc"
	"google.golang.org/grpc/health"
	healthpb "google.golang.org/grpc/health/grpc_health_v1"
	"net"
)

func main() {
	// 关闭处理（释放资源等）
	defer shutdown.Handle()

	// 加载服务端mTLS凭证
	creds, err := util.LoadServerMTLSCredentials()
	if err != nil {
		panic(fmt.Sprintf("加载mTLS凭证失败: %v", err))
	}

	// 监听端口
	lis, err := net.Listen("tcp", config.ServerAddr)
	if err != nil {
		panic(fmt.Sprintf("无法监听地址[%s]: %v", config.ServerAddr, err))
	}
	fmt.Printf("gRPC %s 启动成功，监听地址: 127.0.0.1%s\r\n", config.ServerDesc, config.ServerAddr)

	// 创建gRPC服务器，并添加日志拦截器
	s := grpc.NewServer(grpc.Creds(creds))

	// 注册订单服务
	orderpb.RegisterOrderServiceServer(s, handler.NewOrderHandler())

	// 注册健康检查服务
	healthpb.RegisterHealthServer(s, health.NewServer())

	// 启动服务
	if err := s.Serve(lis); err != nil {
		panic(fmt.Sprintf("服务启动失败: %v", err))
	}
}
